﻿Option Infer On
#Const ADMultiServer = False
Imports System
Imports System.IO
Imports System.Net
Imports System.Data
Imports System.Windows
Imports System.Runtime.Remoting
Imports System.Windows.Controls
Imports System.Windows.Data
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Navigation
Imports Microsoft.VisualBasic, CoreFX, CoreFX.Logging, ChatEngine.Client.Channel, ChatEngine, CoreFX.API, ChatEngine.ServerManagement, ChatEngine.Client, CoreFX.AppDomains, CoreFX.AppDomains.Communication
Partial Public Class MChatAgent
    Dim ChatEngineInstance As ChatEngine.Client.IRCClient
    Dim textC As New System.Text.UTF8Encoding
    Dim toConvert() As Byte
    Delegate Sub DisplayMessage(ByVal E As ShowMessageArgs)
    Delegate Sub LookForTab(ByVal ChannelName As String)
    Dim Channel As ChatEngine.Client.Channel.IRCChannel
    Delegate Sub Nav()
    Delegate Sub AddToConsole(ByVal Info As String)
    Dim b, a, CName As String
    Dim WithEvents NCW As mchatstart.Window1
    Dim IsAutoJoin As Boolean
    Dim HSFStory As Storyboard
    Dim ChatTab As Object
    Dim sellbItem As Object
    Dim LSI As LogSearch.LogIndexer
    Dim serverName As String
    Dim servtoconn As Server
    Dim ConsoleCreated As Boolean
    Dim traywin As CoreFX.trayicon
    Dim notico As Forms.NotifyIcon
#Region " Core Functions"
    Private Sub CTabButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
    End Sub
    Public Sub New()
        MyBase.New()
        Me.InitializeComponent()
        chananme.IsEnabled = False
        notico = New Forms.NotifyIcon()
        traywin = New CoreFX.trayicon()
        notico.Icon = traywin.Icon
        notico.Visible = True
        If NCW Is Nothing Then NCW = New Window1
        If System.Diagnostics.Debugger.IsAttached = True Then
            Tblabel.Content = "Server List (Debug)"
            Me.Title = "Server List (Debug)"
            Button1.Visibility = Windows.Visibility.Visible
        End If
        SharedVars.BuildString = My.Application.Info.Version.BuildString
    End Sub
    Private Sub HandleDisconnect()
        My.Computer.Audio.PlaySystemSound(System.Media.SystemSounds.Beep)
        ChatEngineInstance = Nothing
        NCW.HandleDisconnect()
        notico.BalloonTipIcon = Forms.ToolTipIcon.Warning
        notico.BalloonTipText = "You have been disconnected from " & servtoconn.name
        My.Computer.Audio.PlaySystemSound(System.Media.SystemSounds.Beep)
        notico.BalloonTipTitle = "MChat Disconnected"
        notico.ShowBalloonTip(10000)
        My.Computer.Audio.PlaySystemSound(System.Media.SystemSounds.Beep)
        'ConnectThread = Nothing
    End Sub
    Private Sub TabIsLoaded_Changed()
        Dim I As Integer
        For Each Item As ChatEngine.Client.Channel.ChannelItem In SharedVars.Channels
            If Item.ChanObj.TabIsLoaded = True Then
                I = I + 1
            End If
        Next
        If I = SharedVars.Channels.Count Then
            [Global].Services.Get(Of Interfaces.ILogging).AddItem("TabIsLoaded_Changed: Load queue items here", MessageType.FeedEngine_FMSF)
        End If
    End Sub
#End Region
#Region " Buttons"
    Private Sub Close_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles CloseWindow.MouseDown
        Dim ISC As New ImageSourceConverter
        CloseWindow.Source = ISC.ConvertFrom("pack://application:,,,/Images/Close-pressed.png")
    End Sub
    Private Sub Close_MouseEnter(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles CloseWindow.MouseEnter
        Dim ISC As New ImageSourceConverter
        CloseWindow.Source = ISC.ConvertFrom("pack://application:,,,/Images/close-hover.png")
    End Sub
    Private Sub Close_MouseLeave(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles CloseWindow.MouseLeave
        Dim ISC As New ImageSourceConverter
        CloseWindow.Source = ISC.ConvertFrom("pack://application:,,,/Images/close.png")
    End Sub
    Private Sub Close_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles CloseWindow.MouseUp
        Dim ISC As New ImageSourceConverter
        CloseWindow.Source = ISC.ConvertFrom("pack://application:,,,/Images/close.png")
        If Not IsNothing(ChatEngineInstance) Then ChatEngineInstance.Disconnect()
        Me.Close()
        End
    End Sub
    Private Sub Min_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Min.MouseDown
        Dim ISC As New ImageSourceConverter
        Min.Source = ISC.ConvertFrom("pack://application:,,,/Images/Minimize-pressed.png")
    End Sub
    Private Sub Min_MouseEnter(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles Min.MouseEnter
        Dim ISC As New ImageSourceConverter
        Min.Source = ISC.ConvertFrom("pack://application:,,,/Images/Minimize-hover.png")
    End Sub
    Private Sub Min_MouseLeave(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles Min.MouseLeave
        Dim ISC As New ImageSourceConverter
        Min.Source = ISC.ConvertFrom("pack://application:,,,/Images/Minimize.png")
    End Sub
    Private Sub Min_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Min.MouseUp
        Dim ISC As New ImageSourceConverter
        Min.Source = ISC.ConvertFrom("pack://application:,,,/Images/Minimize.png")
        Me.WindowState = Windows.WindowState.Minimized
    End Sub
#End Region
#Region " Event Handlers"
    Private Sub MChatAgent_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        Try
            lvservers.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Normal, New Nav(AddressOf LoadServers))
            'If System.Diagnostics.Debugger.IsAttached = False Then LSI = New LogSearch.LogIndexer
            If Not IsNothing(LSI) Then [Global].Services.Get(Of Interfaces.ILogging).AddItem("MChatAgent_ctor: " & LSI.ReportIndexStatus(), MessageType.General)
            Dim ADCommServer As ADCommServer = New ADCommServer
        Catch ex As Exception
            ' SharedVars.Services.Get(Of CoreFX.Interfaces.ILogging).AddItem("MChatAgent_Loaded: " & ex.ToString, CoreFX.Logging.MessageType.General)
        End Try
    End Sub
    Private Sub servers_Mdblclick(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles lvservers.MouseDoubleClick
        Try
            Dim A = CType(lvservers.Items(lvservers.SelectedIndex), System.Data.DataRowView).Item(0)
            If IsNothing(A) Then Exit Sub
            servtoconn = SharedVars.Servers.Find(A)
            serverName = servtoconn.name
            Connect.IsEnabled = True
#If ADMultiServer Then
            ICCreateConnection(serverName)
#Else
            InitConnection(serverName)
#End If
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
    Private Sub lvservers_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles lvservers.MouseUp
        Dim A = CType(lvservers.Items(lvservers.SelectedIndex), System.Data.DataRowView).Item(0)
        If IsNothing(A) Then Exit Sub
        servtoconn = SharedVars.Servers.Find(A)
        Connect.IsEnabled = True
    End Sub
    Private Sub LogBrowser_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles LogBrowser.Click
        Dim LBrow As LogViewer = New LogViewer
        LBrow.Show()
    End Sub
    Private Sub AboutButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles AboutButton.Click
        Dim ABWin As About = New About
        ABWin.Show()
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
        For Each ichan As Runtime.Remoting.Channels.IChannel In System.Runtime.Remoting.Channels.ChannelServices.RegisteredChannels
            a = a & ichan.ChannelName
        Next
        MsgBox(a)
    End Sub
    Private Sub Titlebar_MouseLeftButtonDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Titlebar.MouseLeftButtonDown
        Me.DragMove()
    End Sub
    Private Sub Connect_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Connect.Click
        Dim A = CType(lvservers.Items(lvservers.SelectedIndex), System.Data.DataRowView).Item(0)
        If IsNothing(A) Then Exit Sub
#If ADMultiServer Then
        ICCreateConnection(A.ToString)
#Else
        InitConnection(A.ToString)
#End If
    End Sub
    Private Sub chananme_GotFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles chananme.GotFocus
        chananme.Text = ""
        chananme.FontStyle = FontStyles.Normal
    End Sub
    Private Sub ConnectToServerThread(ByVal ServerName As String)
        Dim ServerVar = From svar As Server In SharedVars.Servers Where svar.name Like ServerName
#If ADMultiServer Then
        AppDomains.ConnectionBroker.CreateNewConnection(ServerVar(0), NCW)
#Else
        ChatEngineInstance.ConnectToServer(ServerVar(0).address, ServerVar(0).port)
#End If
    End Sub
    Private Sub chananme_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles chananme.KeyDown
        If e.Key = Input.Key.Enter And chananme.Text <> "" Then
            ChatEngineInstance.JoinChannel(chananme.Text)
        End If
    End Sub
    Private Sub chananme_LostFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles chananme.LostFocus
        chananme.Text = "Join a channel"
        chananme.FontStyle = FontStyles.Italic
    End Sub
    Private Sub NewServer_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles NewServer.Click
        Dim ServOpts As New ConnectToServer
        ServOpts.Show()
    End Sub
    Private Sub MChatAgent_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles Me.Closing
        Try
            ChannelListLoader.SerializeObject(API.GetDataPath() & "Servers.xml", SharedVars.Servers)
            notico.Visible = False
            notico = Nothing
        Catch ex As Exception
            ' SharedVars.Services.Get(Of CoreFX.Interfaces.ILogging).AddItem("MChatAgent_Closing: " & ex.ToString, CoreFX.Logging.MessageType.General)
        End Try
    End Sub
#End Region
#Region " ChatEngine Functions"
    Private Sub CreateIPCServer(ByVal ServerName As String)
        '        ADCommServer.StartServer(ServerName)
        AddHandler RemotingObject.NewConnection, AddressOf StartADClient
        AddHandler RemotingObject.NewChannelEvent, AddressOf NewChannelWin
        AddHandler RemotingObject.NewConsoleLine, AddressOf NewConsoleInfo
    End Sub
    Private Sub StartADClient(ByVal server As String)
        MsgBox(AppDomain.CurrentDomain.FriendlyName, MsgBoxStyle.Information, "New Connection created " & server)
    End Sub
    Private Sub NewConsoleInfo(ByVal Info As String)
        [Global].Services.Get(Of Interfaces.ILogging).AddItem("NewConsoleInfo: " & Info, MessageType.General)
    End Sub
    Private Sub ICCreateConnection(ByVal ServerName As String)
        CreateIPCServer(ServerName)
        Dim ConnectThread As System.Threading.Thread
        'ConnectToServerThread(ServerName)
        ConnectThread = New System.Threading.Thread(AddressOf ConnectToServerThread)
        ConnectThread.Start(ServerName)
    End Sub
    <Obsolete("This function is to be replaced by ICCreateConnction", False)> _
    Private Sub InitConnection(ByVal ServerName As String)
        ChatEngineInstance = New IRCClient
        AddHandler IRCClient.DisconnectedFromServer, AddressOf HandleDisconnect
        AddHandler ChatEngineInstance.Connected, AddressOf Connected
        AddHandler ChatEngineInstance.NewChannel, AddressOf NewChannelWin
        AddHandler ChatEngineInstance.NewQuery, AddressOf NewQuery
        AddHandler ChatEngineInstance.TopicChanged, AddressOf TopicChangedEvent
        AddHandler ChatEngineInstance.InviteToChan, AddressOf InviteUserToChan
        a = GetSetting("MChat", "Settings", "DefaultChannel")
        If System.Diagnostics.Debugger.IsAttached Then
            Me.Tblabel.Content = "Server List (Debug) --- Connecting..."
        Else
            Me.Tblabel.Content = "Server List --- Connecting..."
        End If
        Dim ConnectThread As System.Threading.Thread
        'ConnectToServerThread(ServerName)
        ConnectThread = New System.Threading.Thread(AddressOf ConnectToServerThread)
        ConnectThread.Start(ServerName)
    End Sub
    Private Sub NCWClosed(ByVal sender As Object, ByVal e As EventArgs)
        RemoveHandler IRCClient.DisconnectedFromServer, AddressOf HandleDisconnect
        If Connections.IRCConnection.IsConnected = True Then
            RemoveHandler ChatEngineInstance.Connected, AddressOf Connected
            RemoveHandler ChatEngineInstance.NewChannel, AddressOf NewChannelWin
            RemoveHandler ChatEngineInstance.NewQuery, AddressOf NewQuery
            RemoveHandler ChatEngineInstance.TopicChanged, AddressOf TopicChangedEvent
            RemoveHandler ChatEngineInstance.InviteToChan, AddressOf InviteUserToChan
        End If
        ConsoleCreated = False
        GC.Collect()
        Channel = Nothing
        NCW = New Window1
    End Sub
    Private Sub NewChannelWin(ByVal ChannelName As String, ByVal ChannelObj As IRCChannel, Optional ByVal Server As String = "")
        'If NCW Is Nothing Then NCW = New Window1
        Channel = ChannelObj
        AddHandler Channel.TabIsLoadedChanged, AddressOf TabIsLoaded_Changed
        ChannelObj.MakeChatWindow(ChatEngineInstance)
        ShowFCW()
        ChatEngineInstance.RawCommand("WHO " & ChannelObj.ChanName)
    End Sub
    Private Sub ShowFCW()
        AddHandler NCW.Closed, AddressOf NCWClosed
        Connections.IRCConnection.GlobalWindow = NCW
        SharedVars.GlobalChannelWindow = Connections.IRCConnection.GlobalWindow
        If ConsoleCreated = False Then NCW.CreateTab(serverName, True)
        ConsoleCreated = True
        NCW.CreateTab(Channel.ChanName)
        NCW.ChannelObject = Channel
        Window1.ChatEngineInst = ChatEngineInstance
        Channel.ChannelWindow = NCW
        'Channel.ChannelTab = CTab
        ShowCreateFCW()
    End Sub
    Private Sub ShowCreateFCW()
        NCW.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Normal, New Nav(AddressOf FCWShow))
    End Sub
    Private Sub FCWShow()
        If NCW.IsVisible <> True Then NCW.Show()
    End Sub
    Private Sub TopicChangedEvent(ByVal Topic As String, ByVal ChannelName As String)
        Channel.ChanTopic = Topic
    End Sub
    Private Sub InviteUserToChan(ByVal ChannelName As String)
        ChatEngineInstance.JoinChannel(ChannelName) 'Sends IRC JOIN command
    End Sub
    Private Sub NewQuery(ByVal User As String, ByVal Message As String, ByVal IsFirstMessage As Boolean)
        If IsFirstMessage = True Then
            NCW.CreateTab(User)
            Window1.ChatEngineInst = ChatEngineInstance
            Channel.ChannelWindow = NCW
            Dim msgargs As ShowMessageArgs
            If Not IsNothing(Message) Then
                msgargs = New ShowMessageArgs(User, Message, ShowMessageArgs.MsgTypeEnum.NewChanMsg, User)
                NCW.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.ApplicationIdle, New DisplayMessage(AddressOf NCW.ShowContentInPage), msgargs)
            End If
        Else
            Dim msgargs As ShowMessageArgs
            msgargs = New ShowMessageArgs(User, Message, ShowMessageArgs.MsgTypeEnum.NewChanMsg, User)
            NCW.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.ApplicationIdle, New DisplayMessage(AddressOf NCW.ShowContentInPage), msgargs)
        End If
    End Sub
    Private Sub Connected()
        a = servtoconn.username
        toConvert = Convert.FromBase64String(servtoconn.password)
        b = textC.GetString(toConvert)
        ChatEngineInstance.Login(a, b, a)
        chananme.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Normal, New Nav(AddressOf EnableChanBox))
    End Sub
    Private Sub EnableChanBox()
        If System.Diagnostics.Debugger.IsAttached Then
            Me.Tblabel.Content = "Server List (Debug)"
            Me.Title = "MChat (Debug)"
        Else
            Me.Tblabel.Content = "Server List"
            Me.Title = "MChat"
        End If
        chananme.IsEnabled = True
    End Sub
#End Region
    Private Function CreateDataTable() As DataTable
        Dim tbl As DataTable = New DataTable("SearchResults")
        Dim I As Integer
        tbl.Columns.Add("Server")
        tbl.Columns.Add("Username")
        For Each Item As Server In SharedVars.Servers
            I = I + 1
            tbl.Rows.Add(Item.name, Item.username)
        Next
        Return tbl
    End Function
    Private Sub LoadServers()
        If File.Exists(API.GetDataPath() & "Servers.xml") Then SharedVars.Servers = ChannelListLoader.DeserializeObject(API.GetDataPath() & "Servers.xml")
        Dim lvDTable As DataTable = CreateDataTable()
        lvservers.DataContext = lvDTable
    End Sub
End Class